<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/2/7 16:21
 */
declare(strict_types=1);

namespace App\Service;

use App\Bean\User;
use App\Bean\UserBean;
use App\Dao\UserDao;
use App\Dao\UserJobDao;
use App\Exception\Api\ModelNotFoundException;
use App\Exception\EntityExistException;
use App\Model\UserModel;

/**
 * Author:   XueSi
 * DateTime: 2024/2/7 16:22
 *
 * Class UserService
 *
 * @package App\Service
 */
class UserService extends BaseService
{
    /**
     * Note:     [findByUsername Description]
     * Author:   longhui.huang <1592328848@qq.com>
     * DateTime: 2024/2/1 12:59
     *
     * @param string $username
     *
     * @return UserModel|\App\Model\BaseModel|array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function findByUsername(string $username)
    {
        /** @var UserDao $user */
        $user = app(UserDao::class);
        return $user->getOne(['username' => $username]);
    }

    /**
     * 根据ID查询
     *
     * @param int $id
     *
     * @return UserModel|null
     */
    public function findById(int $id)
    {
        /** @var UserDao $user */
        $user = app(UserDao::class);
        return $user->getOne(['userId' => $id]);
    }

    /**
     * 新增用户
     *
     * @param UserBean $userBean
     *
     * @throws EntityExistException
     */
    public function create(UserBean $userBean): void
    {
        $userBean->setDeptId($userBean->getDept()->getId());

        /** @var UserDao $userDao */
        $userDao = app(UserDao::class);

        if ($userDao->findByUsername($userBean->getUsername())) {
            throw new EntityExistException($userDao, 'username', $userBean->getUsername());
        }

        if ($userDao->findByEmail($userBean->getEmail())) {
            throw new EntityExistException($userDao, 'email', $userBean->getEmail());
        }

        if ($userDao->findByPhone($userBean->getPhone())) {
            throw new EntityExistException($userDao, 'phone', $userBean->getPhone());
        }

        $userJobDao = app(UserJobDao::class);
    }

    // 编辑用户
    public function update()
    {

    }

    // 删除用户
    public function delete(array $ids)
    {

    }

    /**
     * 根据用户名查询
     *
     * @param string $username
     *
     * @return UserModel
     */
    public function getLoginData(string $username): UserModel
    {
        /** @var UserDao $userDao */
        $userDao = app(UserDao::class);
        /** @var UserModel $user */
        $user = $userDao->findByUsername($username);
        if (!$user) {
            throw new ModelNotFoundException(UserModel::class, 'name', $username);
        }

        return $user;
    }
}
